package com.ryskoo.permission.dept.repository;

import com.ryskoo.framework.core.repository.BasicJPAImpl;
import com.ryskoo.permission.dept.domain.DeptPO;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author Shawn
 */
@Repository
public class DeptJPAImpl extends BasicJPAImpl<DeptPO> implements
		IDeptRepository {

	@Override
	public List<DeptPO> getByParentId(String parentId) {

		String hql = "select o from  DeptPO o where 1=1";

		// 如果没有父菜单，则查询一级菜单
		if (StringUtils.isEmpty(parentId)) {
			hql += " and (o.parentID = '' or o.parentID is null)";
		} else {
			hql += " and o.parentID = :parentId";
		}
		
		hql += " and (o.salesManId = '' or o.salesManId is null)";
		
		Query query = getH4Session().createQuery(hql);

		if (!StringUtils.isEmpty(parentId)) {
			query.setString("parentId", parentId);
		}
		return query.list();
	}

	@Override
	public List<DeptPO> getDeptByParentIdAndSalesManId(String parentId, String salesManId) {
		String hql = "select o from  DeptPO o where 1=1";

		hql += " and o.salesManId = :salesManId";
		// 如果没有父菜单，则查询一级菜单
		if (StringUtils.isEmpty(parentId)) {
			hql += " and (o.parentID = '' or o.parentID is null)";
		} else {
			hql += " and o.parentID = :parentId";
		}
		Query query = getH4Session().createQuery(hql);

		if (!StringUtils.isEmpty(parentId)) {
			query.setString("parentId", parentId);
		}
		query.setString("salesManId", salesManId);
		
		return query.list();
	}
}
